package org.mm.proxycache.util;

import java.util.Date;
import java.util.Locale;

import org.mm.proxycache.http.HttpUrl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ch.qos.logback.core.LayoutBase;

public class AccessLayout extends LayoutBase<AccessEvent>
{

    public String doLayout( AccessEvent e )
    {
        double ts = e.timeStamp().getTime() / 1000.0;

        StringBuilder sb = new StringBuilder( 200 );
        try
        {
            Date start = e.request().date();
            Date end = new Date();
            long requestTime = end.getTime() - start.getTime();

            sb.append( String.format( Locale.US, "%.03f %6d ", ts, requestTime ) );

            sb.append( e.clientAddress() ).append( ' ' );
            sb.append( e.type() ).append( '/' ).append( e.response().status().getCode() ).append(
                    ' ' );
            sb.append( e.response().realSize() ).append( ' ' );

            sb.append( e.request().method() ).append( ' ' );

            HttpUrl url = e.request().url().clone();
            url.setSchema( "http" );
            url.setHost( e.request().header( "Host" ) );
            sb.append( url );

            sb.append( " - " ); // ident lookup is always disabled

            if ( e.serverSession() != null )
            {
                sb.append( "DIRECT/" ).append( e.serverAddress() ).append( ' ' );
            }
            else
                sb.append( "NONE/- " );

            String contentType = e.response().contentType();
            if ( contentType != null )
            {
                contentType = contentType.split( ";" )[0];
                sb.append( contentType );
            }
            sb.append( '\n' );

        }
        catch (Throwable t)
        {
            log.debug( "Error:", t );
            return "";
        }

        return sb.toString();
    }

    private static Logger log = LoggerFactory.getLogger( AccessLayout.class );
}
